//
// Created by Administrator on 2025/8/8.
//

#ifndef STACKLIST_H
#define STACKLIST_H
#include<iostream>
namespace stack_lsit {
    struct node {
        explicit node(int data=0) : data(data), next_(nullptr) {}
        int data;
        node* next_;
    };

class stacklist {
public:
    stacklist() {
        head_ = new node();
    }
    ~stacklist() {
        const node* p = head_;
        while(p!=nullptr) {
            head_ = head_->next_;
            delete p;
            p = head_;
        }
    }
    //入栈
    void push(const int data) {
        auto p = new node(data);
        p->next_ = head_->next_;
        head_->next_ = p;
    }
    //出栈
    void pop() {
        if (head_->next_ != nullptr) {
            auto p = head_->next_;
            head_->next_ = p->next_;
            delete p;
        }
    }
    //查看栈顶元素
    int top() const {
        if (head_->next_ == nullptr) {
            throw std::runtime_error("stack is empty");
        }
        return head_->next_->data;
    }
    //判断栈是否为空
    bool empty() const {
        return head_->next_ == nullptr;
    }
    //打印栈
    void print() const {
        for (auto p = head_->next_; p != nullptr; p = p->next_) {
            std::cout << p->data << " ";
        }
        std::cout << std::endl;
    }
private:
    node* head_;
};

} // stack_lsit

#endif //STACKLIST_H
